<!--
 * @Autor: 张小鹏
 * @Date: 2020-04-22 21:25:00
 * @LastEditors: 张小鹏
 * @LastEditTime: 2020-04-23 23:48:14
 * @description: 
 -->
<template>
  <div class="treeselect">
    <div
      class="el-select"
      :class="[selectSize ? 'el-select--' + selectSize : '']"
      @click.stop="toggleMenu"
      v-clickoutside="handleClose"
    >
      <el-popover placement="bottom" title width="300" trigger="click" content>
        <el-input
          slot="reference"
          ref="reference"
          v-model="selectedLabel"
          type="text"
          :placeholder="currentPlaceholder"
          :name="name"
          :id="id"
          :autocomplete="autoComplete || autocomplete"
          :size="selectSize"
          :disabled="selectDisabled"
          :readonly="readonly"
          :validate-event="false"
          :class="{ 'is-focus': visible }"
          :tabindex="(multiple && filterable) ? '-1' : null"
          @focus="handleFocus"
          @blur="handleBlur"
          @keyup.native="debouncedOnInputChange"
          @keydown.native.down.stop.prevent="navigateOptions('next')"
          @keydown.native.up.stop.prevent="navigateOptions('prev')"
          @keydown.native.enter.prevent="selectOption"
          @keydown.native.esc.stop.prevent="visible = false"
          @keydown.native.tab="visible = false"
          @paste.native="debouncedOnInputChange"
          @mouseenter.native="inputHovering = true"
          @mouseleave.native="inputHovering = false"
        >
          <template slot="prefix" v-if="$slots.prefix">
            <slot name="prefix"></slot>
          </template>
          <template slot="suffix">
            <i
              v-show="!showClose"
              :class="['el-select__caret', 'el-input__icon', 'el-icon-' + iconClass]"
            ></i>
            <i
              v-if="showClose"
              class="el-select__caret el-input__icon el-icon-circle-close"
              @click="handleClearClick"
            ></i>
          </template>
        </el-input>
        <el-scrollbar
          tag="ul"
          wrap-class="el-select-dropdown__wrap"
          view-class="el-select-dropdown__list"
          ref="scrollbar"
          :class="{ 'is-empty': !allowCreate && query && filteredOptionsCount === 0 }"
          v-show=" !loading"
        >
          <el-tree
            ref="treeselectwarp"
            v-bind="$attrs"
            v-on="treeselectListeners"
            
          ></el-tree>
        </el-scrollbar>
      </el-popover>
    </div>
  </div>
</template>
<script type="text/babel">
import Emitter from "element-ui/src/mixins/emitter";
import Focus from "element-ui/src/mixins/focus";
import Locale from "element-ui/src/mixins/locale";
import ElInput from "element-ui/packages/input";
import ElSelectMenu from "element-ui/packages/select/src/select-dropdown.vue";
import ElScrollbar from "element-ui/packages/scrollbar";
import Clickoutside from "element-ui/src/utils/clickoutside";
import scrollIntoView from "element-ui/src/utils/scroll-into-view";
import NavigationMixin from "element-ui/packages/select/src/navigation-mixin";
export default {
  mixins: [Emitter, Locale, Focus("reference"), NavigationMixin],
  name: "TreeSelect",
  components: {
    ElInput,
    ElSelectMenu,
    ElScrollbar
  },
  directives: { Clickoutside },
  props: {
    name: String,
    id: String,
    popperAppendToBody: {
      type: Boolean,
      default: true
    },
    autocomplete: {
      type: String,
      default: "off"
    },
    /** @Deprecated in next major version */
    autoComplete: {
      type: String,
      validator(val) {
        process.env.NODE_ENV !== "production" &&
          console.warn(
            "[Element Warn][Select]'auto-complete' property will be deprecated in next major version. please use 'autocomplete' instead."
          );
        return true;
      }
    },
    allowCreate: Boolean,
    loading: Boolean
  },
  computed: {
    treeselectListeners(){
      var vm = this;
      // `Object.assign` 将所有的对象合并为一个新对象
      return Object.assign({},
        // 我们从父级添加所有的监听器
        this.$listeners,
        // 然后我们添加自定义监听器，
        // 或覆写一些监听器的行为
        {
          // 这里确保组件配合 `v-model` 的工作
          'check-change': function (event) {
             let NodesLists=vm.treeselectwarp.getCheckedNodes(true);
             let Labellist=NodesLists.map(obj => {return obj.label});
             let GetValues=NodesLists.map(obj => {return obj.id});
             vm.selectedLabel=Labellist;
             vm.$emit('check-change',GetValues)
           
          }
        }
      )
    
    },
    treeselectwarp() {
      return this.$refs.treeselectwarp;
    },
    selectSize() {
      return this.size || this._elFormItemSize || (this.$ELEMENT || {}).size;
    },
    iconClass() {
      return this.remote && this.filterable
        ? ""
        : this.visible
        ? "arrow-up is-reverse"
        : "arrow-up";
    },
    emptyText() {
      if (this.loading) {
        return this.loadingText || this.t("el.select.loading");
      } else {
        if (this.remote && this.query === "" && this.options.length === 0)
          return false;
        if (
          this.filterable &&
          this.query &&
          this.options.length > 0 &&
          this.filteredOptionsCount === 0
        ) {
          return this.noMatchText || this.t("el.select.noMatch");
        }
        if (this.options.length === 0) {
          return this.noDataText || this.t("el.select.noData");
        }
      }
      return null;
    },
    readonly() {
      return (
        !this.filterable ||
        this.multiple ||
        (!isIE() && !isEdge() && !this.visible)
      );
    },

    showClose() {
      let hasValue = this.multiple
        ? Array.isArray(this.value) && this.value.length > 0
        : this.value !== undefined && this.value !== null && this.value !== "";
      let criteria =
        this.clearable &&
        !this.selectDisabled &&
        this.inputHovering &&
        hasValue;
      return criteria;
    },
    selectDisabled() {
      return this.disabled || (this.elForm || {}).disabled;
    },
    showNewOption() {
      let hasExistingOption = this.options
        .filter(option => !option.created)
        .some(option => option.currentLabel === this.query);
      return (
        this.filterable &&
        this.allowCreate &&
        this.query !== "" &&
        !hasExistingOption
      );
    }
  },
  data() {
    return {
      multiple: false,
      cachedOptions: [],
      createdLabel: null,
      createdSelected: false,
      selected: this.multiple ? [] : {},
      inputLength: 20,
      inputWidth: 0,
      initialInputHeight: 0,
      cachedPlaceHolder: "",
      optionsCount: 0,
      filteredOptionsCount: 0,
      visible: false,
      softFocus: false,
      selectedLabel: "",
      hoverIndex: -1,
      query: "",
      previousQuery: null,
      inputHovering: false,
      currentPlaceholder: "",
      menuVisibleOnFocus: false,
      isOnComposition: false,
      isSilentBlur: false
    };
  },
  methods: {
    toggleMenu() {
      if (!this.selectDisabled) {
        if (this.menuVisibleOnFocus) {
          this.menuVisibleOnFocus = false;
        } else {
          this.visible = !this.visible;
        }
        if (this.visible) {
          (this.$refs.input || this.$refs.reference).focus();
        }
      }
    },
    handleClose() {
      this.visible = false;
    },
    handleFocus(event) {
      if (!this.softFocus) {
        if (this.automaticDropdown || this.filterable) {
          this.visible = true;
          if (this.filterable) {
            this.menuVisibleOnFocus = true;
          }
        }
        this.$emit("focus", event);
      } else {
        this.softFocus = false;
      }
    },

    blur() {
      this.visible = false;
      this.$refs.reference.blur();
    },
    handleBlur(event) {
      setTimeout(() => {
        if (this.isSilentBlur) {
          this.isSilentBlur = false;
        } else {
          this.$emit("blur", event);
        }
      }, 50);
      this.softFocus = false;
    },
    doDestroy() {
      this.$refs.popper && this.$refs.popper.doDestroy();
    },
    handleMenuEnter() {
      this.$nextTick(() => this.scrollToOption(this.selected));
    },
    scrollToOption(option) {
      const target =
        Array.isArray(option) && option[0] ? option[0].$el : option.$el;
      if (this.$refs.popper && target) {
        const menu = this.$refs.popper.$el.querySelector(
          ".el-select-dropdown__wrap"
        );
        scrollIntoView(menu, target);
      }
      this.$refs.scrollbar && this.$refs.scrollbar.handleScroll();
    }
  }
};
</script>